/**
 * 
 */
package com.jiang.utils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author Administrator
 * @文件上传工具类
 */
public class FileUploadUtils {

	private FileUploadUtils() {

	}

	/**
	 * 创建文件名称
	 * 
	 * @param mime
	 * @return
	 */
	public static String createFileName(String mime) {
		if (StringUtils.isNotBlank(mime)) {
			return UUID.randomUUID() + "." + mime.split("/")[1];
		}
		return "";
	}

	/**
	 * 文件保存
	 * 
	 * @param file
	 * @param destFile
	 * @return
	 */
	public static boolean save(MultipartFile file, File destFile) {

		boolean flag = true;
		// 判断父文件夹是否存在
		if (!destFile.getParentFile().exists()) {
			destFile.getParentFile().mkdirs();
		}
		OutputStream out = null;
		InputStream inputStream = null;
		try {
			byte[] data = new byte[2048]; // 保存上传数据
			int len = 0;
			inputStream = file.getInputStream();
			out = new FileOutputStream(destFile);
			while ((len = inputStream.read(data)) != -1) {
				out.write(data, 0, len);
			}
		} catch (FileNotFoundException e) {
			flag = false;
			e.printStackTrace();
		} catch (IOException e) {
			flag = false;
			e.printStackTrace();
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return flag;
	}

}
